import React, { useRef,Component } from 'react';
import { View, Button, Alert } from 'react-native';
import { RNCamera } from 'react-native-camera';
import axios from 'axios';
import {Dialog} from '@rneui/themed';
import {inject,observer } from "mobx-react";
import ImagePicker from 'react-native-image-crop-picker';


@inject("rootStore") // 注入 用来获取 全局数据的
@observer //  当全局发生改变了  组件的重新渲染 从而显示最新的数据
class TakePhoto extends Component {
    constructor(props) {
      super(props);
      this.cameraRef = React.createRef();
      this.state = {
        visible2: false,
        visible3: false,
        photoUri: null,
        rotation: 0,
        time:0
      };
    }
    //启动计时器
    startTick() {
      this.timerID = setInterval(
        () => this.tick(),
        1000 // 每秒触发一次
      );
    }

    //计时器
    tick() {
      this.setState({
        time: this.state.time + 1
      });
    }
      //相册上传
      handleChoosePhoto = () => {
        ImagePicker.openPicker({
          cropping: true,
        }).then(async (image) => { // 将then块转换为异步函数

          // 在这里调用上传图片的函数，使用 image.path 作为上传的图片路径
          const base64Image = await this.convertImageToBase64(image.path); // 使用await等待异步操作完成
          this.uploadPhoto(base64Image);
        }).catch(error => {
          console.error('选择图片时出错:', error);
        });
      };

    // 将图像文件转换为 Base64 编码
  convertImageToBase64 = async (uri) => {
    try {
      // 使用 fetch API 读取图像文件
      const response = await fetch(uri);
      const blob = await response.blob();

      // 使用 FileReader API 将图像文件转换为 Base64 编码
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
          const base64Data = reader.result.split(',')[1];
          resolve(base64Data);
        };
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      });
    } catch (error) {
      console.error('Error converting image to Base64:', error);
      throw error;
    }
  }; 
    //裁剪图片
    rotateImage = async () => {
      this.setState({visible3:false})
      const { photoUri, rotation } = this.state;
      try {
        const rotatedImage = await ImagePicker.openCropper({
          path: photoUri,
          width: 7000,
          height: 9000,
          cropperCircleOverlay: false, // 如果您需要圆形裁剪，请设置为 true
          cropperChooseText: '确定',
          cropperCancelText: '取消',
          cropperToolbarTitle: '编辑图像',
          freeStyleCropEnabled: false, // 允许自由裁剪 
          enableRotationGesture: true, // 启用旋转手势
          rotateDegree: rotation + 90, // 将旋转角度增加 90 度
        });
        this.setState({ photoUri: rotatedImage.path, rotation: rotation + 90 });
        // 读取图像文件并转换为 Base64 编码
        const base64Image = await this.convertImageToBase64(rotatedImage.path);
        this.uploadPhoto(base64Image)
      } catch (error) {
        console.error('Error rotating image:', error);
      }
    };

    //关闭加载中
    toggleDialog3 = () => { 
      this.setState({visible3:false})
    };
    toggleDialog2 = () => {
      clearInterval(this.timerID);
      this.setState({time:0})
      this.setState({visible2:false})
    };

    //拍照
    takePicture = async () => {
      this.setState({visible3:true})
      if (this.cameraRef.current) {
        try {
          const options = {
            quality: 1,
            base64: true,
            height: 9000,
            width: 7000,
          };
          // const data = await this.cameraRef.current.takePictureAsync(options);
          const data = await this.cameraRef.current.takePictureAsync(options);
          // console.log('Photo data:', data);
          this.setState({photoUri: data.uri})
          if(this.state.visible3){
            this.rotateImage()
          }else{
            return
          }
          // this.props.navigation.navigate('photoScreen', { photoUri: data.uri });
          // this.uploadPhoto(data.base64);
        } catch (error) {
          console.error('Error taking picture:', error);
          Alert.alert('拍照失败：', error.message);
          this.setState({visible3:false})
        }
      }
    };
  //上传
    uploadPhoto = async (base64Data) => {
      this.startTick();
      this.setState({visible2:true})
      try {
        // 发送POST请求将照片数据上传到服务器
        const response = await axios.post(this.props.rootStore.ip+"/up_photo", { imageData: base64Data,name:this.props.rootStore.pg });
        console.log('Photo uploaded:', response.data);
        const data= response.data
        if(data.code==200){
          this.props.rootStore.tOrf=data.data.tOrf;
          this.props.rootStore.point=data.data.point;
          this.props.rootStore.img=data.data.img;
          if(this.state.visible2){
            this.toggleDialog2()
            //跳转结果页面
            const { navigation } = this.props; 
            navigation.navigate('result')
          }else{
            return;
          }
        }else{
          if(this.state.visible2){
            this.toggleDialog2();
          Alert.alert('未检测到特征点', '请重新尝试');
          }else{
            return;
          }
        }
      } catch (error) {
        if(this.state.visible2){
          this.toggleDialog2();
          console.error('Error uploading photo:', error);
          Alert.alert('失败', '图片上传失败');
        }else{
          return;
        }
      }
    };
  
    render() {
      return (
        <View style={{ flex: 1 }}>
          <RNCamera
            ref={this.cameraRef}
            style={{ flex: 1 }}
            type={RNCamera.Constants.Type.back}
            captureAudio={false}
            fixOrientation={true} 
          />
          <Dialog isVisible={this.state.visible3} onBackdropPress={this.toggleDialog3}>
          <Dialog.Title title="加载中"/>
            <Dialog.Loading />
          </Dialog>
          <Dialog isVisible={this.state.visible2} onBackdropPress={this.toggleDialog2}>
          <Dialog.Title title={"正在鉴别，已等待" + this.state.time +"秒"}/>
            <Dialog.Loading />
          </Dialog>
          <View style={{ flexDirection: 'row', padding: 10 }}>
            <Button style={{ width: 100, height: 40 }} title="上传" onPress={this.handleChoosePhoto} />
            <View style={{ marginLeft:"35%"}}>
              <Button title="拍照" onPress={this.takePicture} />
            </View>
          </View>
        </View>
      );
    }
  }

export default TakePhoto;